<?php
namespace app\common\logic;

use app\common\model\Goods;
use think\facade\Db;
/**
 * 产品
 */
class GoodsLogic
{
    /**
     * 添加产品
     */
    public function afterSave($goods_id,$post)
    {
        // 商品图片相册  图册
        $goods_images = $post['goods_images'];
        if(count($goods_images) > 1)
        {
            array_pop($goods_images); // 弹出最后一个
            $goodsImagesArr = Db::name('GoodsImages')->where("goods_id = $goods_id")->column('image_url','img_id'); // 查出所有已经存在的图片

            // 删除图片
            foreach($goodsImagesArr as $key => $val)
            {
                //dump(file_exists(trim($val,'/')));
                if(!in_array($val, $goods_images) || !file_exists(trim($val,'/'))) Db::name('GoodsImages')->where("img_id = {$key}")->delete();
            }

            //重新取出来
            $goodsImagesArr = Db::name('GoodsImages')->where("goods_id = $goods_id")->column('image_url','img_id'); // 查出所有已经存在的图片
            // 添加图片
            foreach($goods_images as $key => $val)
            {//dump( file_exists(trim($val,'/')));
                if($val == null)  continue;
                if(!in_array($val, $goodsImagesArr) && file_exists(trim($val,'/')))
                {
                    $data = array('goods_id' => $goods_id,'image_url' => $val);
                    Db::name("GoodsImages")->insert($data);
                }
            }
        }

        //主图
        $original_img = $post['original_img'];
        $original_img= trim($original_img,'/');
        if(!file_exists($original_img)){
            $img = Db::name('goods_images')->where("goods_id = $goods_id")->order('img_id asc')->column('image_url');
            Db::name('goods')->where(['goods_id'=>$goods_id])->update(['original_img'=>$img]);
        }
//        $c = Db::name('GoodsImages')->where("goods_id = $goods_id and image_url = '{$original_img}'")->count();
//
//        if($c == 0 && $original_img)
//        {
//            Db::name("GoodsImages")->add(array('goods_id'=>$goods_id,'image_url'=>$original_img));
//        }
        delFile(UPLOAD_PATH."goods/thumb/$goods_id"); // 删除缩略图

        // 商品规格图片处理
        if($post['item_img'])
        {
            Db::name('SpecImage')->where("goods_id = $goods_id")->delete(); // 把原来是删除再重新插入
            foreach ($post['item_img'] as $key => $val)
            {
                if(empty($val)) continue;
                Db::name('SpecImage')->insert(array('goods_id'=>$goods_id ,'spec_item_id'=>$key,'src'=>$val));
            }
        }

        // 商品规格价钱处理
        $goods_item = $post['item'];
        $specStock = Db::name('spec_goods_price')->where('goods_id = '.$goods_id)->column('key,item_id,store_count','key');
        $f_item_id=0;
        if ($goods_item) {
            $keyArr = '';//规格id数组
            $i=1;
            foreach ($goods_item as $k => $v) {
                $data = $v;
                //更新商品的价格等为第一个规格的
                if($i==1){
                    Db::name('Goods')->where(['goods_id'=>$goods_id])->update($data);
                }

                $data['goods_id'] = $goods_id;
                $data['key'] = $k;

                //规格更新
                if (!empty($specStock[$k])) {
                    $item_id = $specStock[$k]['item_id'];
                    $keyArr[] =$item_id;
                    Db::name('spec_goods_price')->where(['item_id' => $item_id])->update($data);
                } else {
                    Db::name('spec_goods_price')->insert($data);
                    $item_id = Db::name('spec_goods_price')->getLastInsID();
                }
                if($i==1){
                    $f_item_id = $item_id;
                }
                //库存
                $stock_log = 0;
                if(!empty($specStock[$k])){
                    if($v['store_count'] != $specStock[$k]['store_count']){
                        $stock = $v['store_count'] - $specStock[$k]['store_count'];
                        $stock_log = 1;
                    }
                }else{
                    $stock = $v['store_count'];
                    $stock_log = 1;
                }
                //记录库存日志
                if($stock_log) {
                    logic('Stock')->update_stock_log(session('admin_id'), $stock, array('goods_id' => $goods_id, 'goods_name' => $post['goods_name'], 'spec_key_name' => $v['key_name'], 'spec_goods_id' => $item_id));
                }

                $i++;
            }
            if($keyArr){
                //删除多余规格
                Db::name('spec_goods_price')->where('goods_id',$goods_id)->whereNotIn('item_id',$keyArr)->delete();
                //删除多余购物车
                Db::name('cart')->where('goods_id',$goods_id)->whereNotIn('spec_goods_id',$keyArr)->delete();
            }
        }else{//没有规格时
            $stock_log = 0;
            if(isset($post['goods_id'])){
                if($post['store_count'] != $post['old_store_count']){
                    $stock = $post['store_count'] - $post['old_store_count'];
                    $stock_log = 1;
                }
            }else{
                $stock = $post['store_count'];
                $stock_log = 1;
            }
            //记录库存日志
            if($stock_log) {
                logic('Stock')->update_stock_log(session('admin_id'), $stock, array('goods_id' => $goods_id, 'goods_name' => $post['goods_name']));
            }
        }

        //更新商品第一个规格id
        Db::name('goods')->where(['goods_id'=>$goods_id])->update(['spec_goods_id'=>$f_item_id]);
        //商品属性
        $this->saveGoodsAttr($goods_id, $post);
    }

    /**
     *  给指定商品添加属性 或修改属性
     */
    public function saveGoodsAttr($goods_id, $post)
    {
        $GoodsAttr = Db::name('GoodsAttr');
        // 属性类型被更改了 就先删除以前的属性类型 或者没有属性 则删除
        if ($post['goods_type'] == 0) {
            $GoodsAttr->where('goods_id = ' . $goods_id)->delete();
            return;
        }

        $GoodsAttrList = $GoodsAttr->where('goods_id = ' . $goods_id)->select();

        $old_goods_attr = array(); // 数据库中的的属性  以 attr_id _ 和值的 组合为键名
        foreach ($GoodsAttrList as $k => $v) {
            $old_goods_attr[$v['attr_id'] . '_' . $v['attr_value']] = $v;
        }

        // post 提交的属性  以 attr_id _ 和值的 组合为键名
        foreach ($post as $k => $v) {
            $attr_id = str_replace('attr_', '', $k);
            if (!strstr($k, 'attr_'))
                continue;
            foreach ($v as $k2 => $v2) {
                $v2 = trim($v2);
                if (empty($v2))continue;

                $tmp_key = $attr_id . "_" . $v2;
                if (!array_key_exists($tmp_key, $old_goods_attr)) // 如果这个属性不存在
                {
                    $GoodsAttr->add(array('goods_id' => $goods_id, 'attr_id' => $attr_id, 'attr_value' => $v2));
                }else{
                    unset($old_goods_attr[$tmp_key]);
                }
            }

        }
        // 没有被 unset($old_goods_attr[$tmp_key]); 掉是 说明 数据库中存在 表单中没有提交过来则要删除操作
        foreach ($old_goods_attr as $k => $v) {
            $GoodsAttr->where('goods_attr_id = ' . $v['goods_attr_id'])->delete();
        }
    }

    /**
     * 获取商品规格
     * @param $goods_id|商品id
     * @return array
     */
    public function get_spec($goods_id)
    {
        //商品规格 价钱 库存表 找出 所有 规格项id
        $keys = Db::name('Goods')->where("goods_id", $goods_id)->column("spec_items");
        $spec = Db::name('Spec')->column('name','id');
        $filter_spec = array();
        if ($keys) {
            $filter_spec2 = unserialize($keys);
            $specImage = Db::name('spec_image')->where(['goods_id'=>$goods_id,'src'=>['<>','']])->column("src","spec_item_id");// 规格对应的 图片表， 例如颜色
            foreach ($filter_spec2 as $key => $val) {
                $spec_name = $spec[$key];
                foreach($val as $k=>$v){
                    $filter_spec[$spec_name][] = array(
                        'item_id' => $k,
                        'item' => $v,
                        'src' => $specImage[$k],
                    );
                }
            }
        }
        return $filter_spec;
    }

    /**
     * 获取某个商品的评论统计
     * c0:全部评论数  c1:好评数 c2:中评数  c3差评数
     * rate1:好评率 rate2:中评率  c3差评率
     * @param $goods_id
     * @return array
     */
    public function commentStatistics($goods_id)
    {
        $commentWhere = ['is_show'=>1,'goods_id'=>$goods_id,'parent_id'=>0,'user_id'=>['gt',0]];
        $c1 = Db::name('comment')->where($commentWhere)->where('ceil((deliver_rank + goods_rank + service_rank) / 3) in (4,5)')->count();
        $c2 = Db::name('comment')->where($commentWhere)->where('ceil((deliver_rank + goods_rank + service_rank) / 3) in (3)')->count();
        $c3 = Db::name('comment')->where($commentWhere)->where('ceil((deliver_rank + goods_rank + service_rank) / 3) in (0,1,2)')->count();
        $c4 = Db::name('comment')->where($commentWhere)->where("img !='' and img NOT LIKE 'N;%'")->count(); // 晒图
        $c0 = $c1 + $c2 + $c3; // 所有评论
        if($c0 <= 0){
            $rate1 = 100;
            $rate2 = 0;
            $rate3 = 0;
        }else{
            $rate1 = ceil($c1 / $c0 * 100); // 好评率
            $rate2 = ceil($c2 / $c0 * 100); // 中评率
            $rate3 = ceil($c3 / $c0 * 100); // 差评率
        }
        return array('c0' => $c0, 'c1' => $c1, 'c2' => $c2, 'c3' => $c3, 'c4'=>$c4,'rate1' => $rate1, 'rate2' => $rate2, 'rate3' => $rate3);
    }

    /**
     * 用户浏览记录
     */
    public function add_visit_log($user_id,$goods){
        $record = Db::name('goods_visit')->where(array('user_id'=>$user_id,'goods_id'=>$goods['goods_id']))->find();
        if($record){
            Db::name('goods_visit')->where(array('user_id'=>$user_id,'goods_id'=>$goods['goods_id']))->save(array('visittime'=>time()));
        }else{
            $visit = array('user_id'=>$user_id,'goods_id'=>$goods['goods_id'],'visittime'=>time(),'cat_id'=>$goods['cat_id']);
            Db::name('goods_visit')->add($visit);
        }
        Db::name('Goods')->where(array('goods_id'=>$goods['goods_id']))->setInc('click_count',1);
    }

    /**
     * 商品收藏
     * @param $user_id|用户id
     * @param $goods_id|商品id
     * @return array
     */
    public function collect_goods($user_id, $goods_id)
    {
        if(!is_numeric($user_id) || $user_id <= 0){
            return array('status'=>-1,'msg'=>'必须登录后才能收藏','result'=>array());
        }
        $exit = Db::name('goods_collect')->where("user_id", $user_id)->where("goods_id", $goods_id)->find();
        if($exit){
            Db::name('goods')->where('goods_id', $goods_id)->setDec('collect_sum');
            Db::name('goods_collect')->where('id',$exit['id'])->delete();
            return array('status'=>1,'msg'=>'取消成功！','result'=>array());
        }else{
            Db::name('goods')->where('goods_id', $goods_id)->setInc('collect_sum');
            Db::name('goods_collect')->insert(array('goods_id'=>$goods_id,'user_id'=>$user_id, 'add_time'=>time()));
            return array('status'=>1,'msg'=>'收藏成功!请到个人中心查看','result'=>array());
        }
    }

    /**
     * 获取共同价格或其他属性,产品，规格，购物车，订单
     * @param  $display 1显示覆盖 0入表
     */
    public function getFilterAttr($dis=1){
        $ary = ['shop_price','market_price','cost_price','weight','store_count'];
        $pricearr = $this->getLxPrice();
        if($pricearr){
            $ary = array_merge($ary,array_keys($pricearr));
        }

        //不需要显示时，即入表操作
        if(!$dis){
            foreach($ary as $key=>$val){
                if($val=='store_count' || $val=='market_price'){
                    unset($ary[$key]);
                }
            }
        }
        return $ary;
    }

    /**
     * 获取商品信息,规格价格覆盖，其他价格覆盖等
     * @data map|order|field|
     */
    public function getList($data,$single=false){
        //查询条件
        $map = [];
        if(isset($data['map'])) $map = $data['map'];
        //排序
        $order = 'goods_id desc';
        if(isset($data['order'])) $order = $data['order'];

        //字段
        $field='*';
        if(isset($data['field'])) $field = $data['field'];

        //获取商品本身--默认就是第一个规格的价格
        if(isset($data['firstRow'])){
            $list = Db::name('Goods')->where($map)->order($order)->field($field)->limit($data['firstRow'],$data['listRows'])->select();
        }else{
            $list = Db::name('Goods')->where($map)->order($order)->field($field)->select();
        }
        //价格转化
        $this->getPrice($list,$data['user_id']);
        if(count($list)==1 && $single){
            return $list[0];
        }else{
            return $list;
        }
    }

    /**
     * 商品其他价格
     */
    public function getPrice(&$list,$user_id=0){
        foreach($list as &$val){
//            if($val['leixing_id']==1){
//                $val['zs_quan'] = $val['shop_price']*$val['pyqrate']/100;
//            }elseif($val['leixing_id']==3){
//                $val['zhekou'] = intval($val['shop_price']/$val['market_price']*100);
//            }
        }
//        //会员折扣价
//        if($user_id>0){
//            $rank = Db::name('Users')->where('user_id',$user_id)->getField('level');
//            $level = Db::name('UserLevel')->getField('rank,discount');
//            $discount = $level[$rank];
//            if($discount<=0 || $discount>100) $discount=100;
//            foreach($list as &$val){
//
//                $val['shop_price'] = $val['shop_price']*$discount/100;
//            }
//        }
    }

    /**
     * 根据配送地址获取多个商品的运费
     * @param $goodsArr
     * @param $region_id
     * @return int
     */
    public function getFreight($goods, $address,$freight_id=0)
    {
        $freightLogic = new FreightLogic();
        $yunfei = [];
        foreach($goods as $suid =>$sval){
            $goodsArr = $sval['goods'];
            $goods_ids = get_arr_column($goodsArr, 'goods_id');
            //获取运费模板
            $goodsList = Db::name('Goods')->where('goods_id', 'IN', $goods_ids)->column('goods_id,template_id,is_free_shipping','goods_id');
            foreach ($goodsArr as $cartKey => $cartVal) {
                $goodsArr[$cartKey]['template_id'] = $goodsList[$cartVal['goods_id']]['template_id'];
                $goodsArr[$cartKey]['is_free_shipping'] = $goodsList[$cartVal['goods_id']]['is_free_shipping'];
            }
            $template_list = [];
            foreach ($goodsArr as $goodsKey => $goodsVal) {
                $template_list[$goodsVal['template_id']][] = $goodsVal;
            }
            $freight = 0;
            $temp = [
                'template_id' => 0,
                'total_weight' => 0,
                'goods_num' => 0,
                'is_free_shipping' => 0,
                'product_price' => 0
            ];
            foreach ($goodsArr as $goodsKey => $goodsVal) {
                $temp['total_weight'] += $goodsVal['weight'] * $goodsVal['goods_num'];
                $temp['goods_num'] += $goodsVal['goods_num'];
                $temp['is_free_shipping'] = $goodsVal['is_free_shipping'];
                $temp['product_price'] = bcmul($goodsVal['shop_price'] , $goodsVal['goods_num'],2);
            }

            $res_freight = $freightLogic->doCalculation($freight_id,$address,$temp['product_price'],$temp['goods_num'],$temp['total_weight']);
            if($res_freight['status']==0){
                return $res_freight;
            }
            $yunfei[$suid] = $res_freight['freight_price'];
        }
        return ['status'=>1,'data'=>$yunfei];
    }

    /**
     * 获取商品类型
     */
    public function getLeixing($sid=0){
        $where = '1=1';
        if($sid){
            $where = ['is_supply'=>1];
        }
        return Db::name('goods_leixing')->where($where)->column('name','id');
    }

    /**
     * 获取类型价格
     * id==0 的情况是获取所有字段
     */
    public function getLxPrice($id='0'){
        $ary = [];
        $config = tpCache('goodsprice');
        if($config){
            foreach($config as $val){
                if(in_array($id,$val['leixing']) || $id==0){
                    $ary[$val['field']] = $val['name'];
                }
            }
        }
        return $ary;
    }





    /**
     * @param $goods_id_arr
     * @param $filter_param
     * @param $action
     * @return array|mixed 这里状态一般都为1 result 不是返回数据 就是空
     * 获取 商品列表页帅选品牌
     */
    public function get_filter_brand($goods_id_arr, $filter_param, $action)
    {
        if (!empty($filter_param['brand_id'])) {
            return array();
        }

        $map['goods_id'] = ['in', $goods_id_arr];
        $map['brand_id'] = ['>', 0];
        $brand_id_arr = Db::name('goods')->where($map)->column('brand_id');
        $list_brand = Db::name('brand')->where('id','in',$brand_id_arr)->limit('30')->select();

        foreach ($list_brand as $k => $v) {
            // 帅选参数
            $filter_param['brand_id'] = $v['id'];
            $list_brand[$k]['href'] = urldecode(U("Goods/$action", $filter_param, ''));
        }
        return $list_brand;
    }

    /**
     * @param $goods_id_arr
     * @param $filter_param
     * @param $action
     * @param int $mode  0  返回数组形式  1 直接返回result
     * @return array 这里状态一般都为1 result 不是返回数据 就是空
     * 获取 商品列表页帅选规格
     */
    public function get_filter_spec($goods_id_arr, $filter_param, $action, $mode = 0)
    {
        $goods_id_str = implode(',', $goods_id_arr);
        $goods_id_str = $goods_id_str ? $goods_id_str : '0';
        $spec_key = DB::query("select group_concat(`key` separator  '_') as `key` from __PREFIX__spec_goods_price where goods_id in($goods_id_str)");  //where("goods_id in($goods_id_str)")->select();
        $spec_key = explode('_', $spec_key[0]['key']);
        $spec_key = array_unique($spec_key);
        $spec_key = array_filter($spec_key);

        if (empty($spec_key)) {
            if ($mode == 1) return array();
            return array('status' => 1, 'msg' => '', 'result' => array());
        }
        $spec = Db::name('spec')->where(array('search_index'=>1))->column('name','id');
        $spec_item = Db::name('spec_item')->where(array('spec_id'=>array('in',array_keys($spec))))->column('spec_id,item','id');

        $list_spec = array();
        $old_spec = $filter_param['spec'];
        foreach ($spec_key as $k => $v) {
            if (strpos($old_spec, $spec_item[$v]['spec_id'] . '_') === 0 || strpos($old_spec, '@' . $spec_item[$v]['spec_id'] . '_') || $spec_item[$v]['spec_id'] == '')
                continue;
            $list_spec[$spec_item[$v]['spec_id']]['spec_id'] = $spec_item[$v]['spec_id'];
            $list_spec[$spec_item[$v]['spec_id']]['name'] = $spec[$spec_item[$v]['spec_id']];
            //$list_spec[$spec_item[$v]['spec_id']]['item'][$v] = $spec_item[$v]['item'];

            // 帅选参数
            if (!empty($old_spec))
                $filter_param['spec'] = $old_spec . '@' . $spec_item[$v]['spec_id'] . '_' . $v;
            else
                $filter_param['spec'] = $spec_item[$v]['spec_id'] . '_' . $v;
            $list_spec[$spec_item[$v]['spec_id']]['item'][] = array('key' => $spec_item[$v]['spec_id'], 'val' => $v, 'item' => $spec_item[$v]['item'], 'href' => urldecode(U("Goods/$action", $filter_param, '')));
        }

        if ($mode == 1) return $list_spec;
        return array('status' => 1, 'msg' => '', 'result' => $list_spec);
    }
    /**
     * @param array $goods_id_arr
     * @param $filter_param
     * @param $action
     * @param int $mode 0  返回数组形式  1 直接返回result
     * @return array
     * 获取商品列表页帅选属性
     */
    public function get_filter_attr($goods_id_arr = array(), $filter_param, $action, $mode = 0)
    {
        $goods_id_str = implode(',', $goods_id_arr);
        $goods_id_str = $goods_id_str ? $goods_id_str : '0';
        $goods_attr = Db::name('goods_attr')->where(['goods_id'=>['in',$goods_id_str],'attr_value'=>['<>','']])->select();
        // $goods_attr = Db::name('goods_attr')->where("attr_value != ''")->select();
        $goods_attribute = Db::name('goods_attribute')->where("attr_index = 1")->column('attr_name,attr_index','attr_id');
        if (empty($goods_attr)) {
            if ($mode == 1) return array();
            return array('status' => 1, 'msg' => '', 'result' => array());
        }
        $list_attr = $attr_value_arr = array();
        $old_attr = $filter_param['attr'];
        foreach ($goods_attr as $k => $v) {
            // 存在的帅选不再显示
            if (strpos($old_attr, $v['attr_id'] . '_') === 0 || strpos($old_attr, '@' . $v['attr_id'] . '_'))
                continue;
            if ($goods_attribute[$v['attr_id']]['attr_index'] == 0)
                continue;
            $v['attr_value'] = trim($v['attr_value']);
            // 如果同一个属性id 的属性值存储过了 就不再存贮
            if (in_array($v['attr_id'] . '_' . $v['attr_value'], (array)$attr_value_arr[$v['attr_id']]))
                continue;
            $attr_value_arr[$v['attr_id']][] = $v['attr_id'] . '_' . $v['attr_value'];

            $list_attr[$v['attr_id']]['attr_id'] = $v['attr_id'];
            $list_attr[$v['attr_id']]['attr_name'] = $goods_attribute[$v['attr_id']]['attr_name'];

            // 帅选参数
            if (!empty($old_attr))
                $filter_param['attr'] = $old_attr . '@' . $v['attr_id'] . '_' . $v['attr_value'];
            else
                $filter_param['attr'] = $v['attr_id'] . '_' . $v['attr_value'];

            $list_attr[$v['attr_id']]['attr_value'][] = array('key' => $v['attr_id'], 'val' => $v['attr_value'], 'attr_value' => $v['attr_value'], 'href' => U("Goods/$action", $filter_param, ''));
            //unset($filter_param['attr_id_'.$v['attr_id']]);
        }
        if ($mode == 1) return $list_attr;
        return array('status' => 1, 'msg' => '', 'result' => $list_attr);
    }







    /**
     * 获取相关分类
     * @param $cat_id|分类id
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function get_siblings_cate($cat_id)
    {
        if (empty($cat_id))
            return array();
        $cate_info = Db::name('goods_category')->where("id", $cat_id)->find();
        $siblings_cate = Db::name('goods_category')->where(['id'=>['<>',$cat_id],'parent_id'=>$cate_info['parent_id']])->select();
        return empty($siblings_cate) ? array() : $siblings_cate;
    }

    /**
     * 看了又看
     */
    public function get_look_see($goods)
    {
        return Db::name('goods')->where(['goods_id'=>['<>',$goods['goods_id']],'cat_id'=>['<>',$goods['cat_id']],'is_on_sale'=>1])->limit(12)->select();
    }


    /**
     * 筛选的价格期间
     * @param $goods_id_arr|帅选的分类id
     * @param $filter_param
     * @param $action
     * @param int $c 分几段 默认分5 段
     * @return array
     */
    function get_filter_price($goods_id_arr, $filter_param, $action, $c = 5)
    {

        if (!empty($filter_param['price']))
            return array();

        $goods_id_str = implode(',', $goods_id_arr);
        $goods_id_str = $goods_id_str ? $goods_id_str : '0';
        $priceList = Db::name('goods')->where("goods_id", "in", $goods_id_str)->column('shop_price');  //where("goods_id in($goods_id_str)")->select();
        rsort($priceList);
        $max_price = (int)$priceList[0];

        $psize = ceil($max_price / $c); // 每一段累积的价钱
        $parr = array();
        for ($i = 0; $i < $c; $i++) {
            $start = $i * $psize;
            $end = $start + $psize;

            // 如果没有这个价格范围的商品则不列出来
            $in = false;
            foreach ($priceList as $k => $v) {
                if ($v > $start && $v < $end)
                    $in = true;
            }
            if ($in == false)
                continue;

            $filter_param['price'] = "{$start}-{$end}";
            if ($i == 0)
                $parr[] = array('value' => "{$end}元以下", 'href' => urldecode(U("Goods/$action", $filter_param, '')));
            elseif($i == ($c-1) && ($max_price > $end))
                $parr[] = array('value' => "{$end}元以上", 'href' => urldecode(U("Goods/$action", $filter_param, '')));
            else
                $parr[] = array('value' => "{$start}-{$end}元", 'href' => urldecode(U("Goods/$action", $filter_param, '')));
        }
        return $parr;
    }

    /**
     * 筛选条件菜单
     * @param $filter_param
     * @param $action
     * @return array
     */
    function get_filter_menu($filter_param, $action)
    {
        $menu_list = array();
        // 品牌
        if (!empty($filter_param['brand_id'])) {
            $brand_list = Db::name('brand')->column('name','id');
            $brand_id = explode('_', $filter_param['brand_id']);
            $brand['text'] = "品牌:";
            foreach ($brand_id as $k => $v) {
                $brand['text'] .= $brand_list[$v] . ',';
            }
            $brand['text'] = substr($brand['text'], 0, -1);
            $tmp = $filter_param;
            unset($tmp['brand_id']); // 当前的参数不再带入
            $brand['href'] = urldecode(U("Goods/$action", $tmp, ''));
            $menu_list[] = $brand;
        }
        // 规格
        if (!empty($filter_param['spec'])) {
            $spec = Db::name('spec')->column('name','id');
            $spec_item = Db::name('spec_item')->column('item','id');
            $spec_group = explode('@', $filter_param['spec']);
            foreach ($spec_group as $k => $v) {
                $spec_group2 = explode('_', $v);
                $spec_menu['text'] = $spec[$spec_group2[0]] . ':';
                array_shift($spec_group2); // 弹出第一个规格名称
                foreach ($spec_group2 as $k2 => $v2) {
                    $spec_menu['text'] .= $spec_item[$v2] . ',';
                }
                $spec_menu['text'] = substr($spec_menu['text'], 0, -1);

                $tmp = $spec_group;
                $tmp2 = $filter_param;
                unset($tmp[$k]);
                $tmp2['spec'] = implode('@', $tmp); // 当前的参数不再带入
                $spec_menu['href'] = urldecode(U("Goods/$action", $tmp2, ''));
                $menu_list[] = $spec_menu;
            }
        }
        // 属性
        if (!empty($filter_param['attr'])) {
            $goods_attribute = Db::name('goods_attribute')->column('attr_name','attr_id');
            $attr_group = explode('@', $filter_param['attr']);
            foreach ($attr_group as $k => $v) {
                $attr_group2 = explode('_', $v);
                $attr_menu['text'] = $goods_attribute[$attr_group2[0]] . ':';
                array_shift($attr_group2); // 弹出第一个规格名称
                foreach ($attr_group2 as $k2 => $v2) {
                    $attr_menu['text'] .= $v2 . ',';
                }
                $attr_menu['text'] = substr($attr_menu['text'], 0, -1);

                $tmp = $attr_group;
                $tmp2 = $filter_param;
                unset($tmp[$k]);
                $tmp2['attr'] = implode('@', $tmp); // 当前的参数不再带入
                $attr_menu['href'] = urldecode(U("Goods/$action", $tmp2, ''));
                $menu_list[] = $attr_menu;
            }
        }
        // 价格
        if (!empty($filter_param['price'])) {
            $price_menu['text'] = "价格:" . $filter_param['price'];
            unset($filter_param['price']);
            $price_menu['href'] = urldecode(U("Goods/$action", $filter_param, ''));
            $menu_list[] = $price_menu;
        }

        return $menu_list;
    }

    /**
     * 传入当前分类 如果当前是 2级 找一级
     * 如果当前是 3级 找2 级 和 一级
     * @param  $goodsCate
     */
    function get_goods_cate(&$goodsCate)
    {
        if (empty($goodsCate)) return array();
        $cateAll = logic('GoodsCategory')->get_goods_category_tree();
        if ($goodsCate['level'] == 1) {
            $cateArr = $cateAll[$goodsCate['id']]['tmenu'];
            $goodsCate['parent_name'] = $goodsCate['name'];
            $goodsCate['select_id'] = 0;
        } elseif ($goodsCate['level'] == 2) {
            $cateArr = $cateAll[$goodsCate['parent_id']]['tmenu'];
            $goodsCate['parent_name'] = $cateAll[$goodsCate['parent_id']]['name'];//顶级分类名称
            $goodsCate['open_id'] = $goodsCate['id'];//默认展开分类
            $goodsCate['select_id'] = 0;
        } else {
            $parent = Db::name('GoodsCategory')->where("id", $goodsCate['parent_id'])->order('`sort_order` desc')->find();//父类
            $cateArr = $cateAll[$parent['parent_id']]['tmenu'];
            $goodsCate['parent_name'] = $cateAll[$parent['parent_id']]['name'];//顶级分类名称
            $goodsCate['open_id'] = $parent['id'];
            $goodsCate['select_id'] = $goodsCate['id'];//默认选中分类
        }
        return $cateArr;
    }

    /**
     * @param  $brand_id|帅选品牌id
     * @param  $price|帅选价格
     * @return array|mixed
     */
    function getGoodsIdByBrandPrice($brand_id, $price)
    {
        if (empty($brand_id) && empty($price))
            return array();
        $brand_select_goods=$price_select_goods=array();
        if ($brand_id) // 品牌查询
        {
            $brand_id_arr = explode('_', $brand_id);
            $brand_select_goods = Db::name('goods')->whereIn('brand_id',$brand_id_arr,'or')->column('goods_id');
        }
        if ($price)// 价格查询
        {
            $price = explode('-', $price);
            $price[0] = intval($price[0]);
            $price[1] = intval($price[1]);
            $price_where=" shop_price >= $price[0] and shop_price <= $price[1] ";
            $price_select_goods = Db::name('goods')->where($price_where)->column('goods_id');
        }
        if($brand_select_goods && $price_select_goods)
            $arr = array_intersect($brand_select_goods,$price_select_goods);
        else
            $arr = array_merge($brand_select_goods,$price_select_goods);
        return $arr ? $arr : array();
    }

    /**
     * 根据规格 查找 商品id
     * @param $spec|规格
     * @return array|\type
     */
    function getGoodsIdBySpec($spec)
    {
        if (empty($spec))
            return array();

        $spec_group = explode('@', $spec);
        $where = " where 1=1 ";
        foreach ($spec_group as $k => $v) {
            $spec_group2 = explode('_', $v);
            array_shift($spec_group2);
            $like = array();
            foreach ($spec_group2 as $k2 => $v2) {
                $v2 = addslashes($v2);
                $like[] = " key2  like '%\_$v2\_%' ";
            }
            $where .= " and (" . implode('or', $like) . ") ";
        }
        $sql = "select * from (select *,concat('_',`key`,'_') as key2 from __PREFIX__spec_goods_price as a) b  $where";
        $result = Db::query($sql);
        $arr = get_arr_column($result, 'goods_id');  // 只获取商品id 那一列
        return ($arr ? $arr : array_unique($arr));
    }

    /**
     * @param $attr|属性
     * @return array|mixed
     * 根据属性 查找 商品id
     * 59_直板_翻盖
     * 80_BT4.0_BT4.1
     */
    function getGoodsIdByAttr($attr)
    {
        if (empty($attr))
            return array();

        $attr_group = explode('@', $attr);
        $attr_id = $attr_value = array();
        foreach ($attr_group as $k => $v) {
            $attr_group2 = explode('_', $v);
            $attr_id[] = array_shift($attr_group2);
            $attr_value = array_merge($attr_value, $attr_group2);
        }
        $c = count($attr_id) - 1;
        if ($c > 0) {
            $arr = Db::name('goods_attr')
                ->where(['attr_id'=>['in',$attr_id],'attr_value'=>['in',$attr_value]])
                ->group('goods_id')
                ->having("count(goods_id) > $c")
                ->column("goods_id");
        }else{
            $arr = Db::name('goods_attr')
                ->where(['attr_id'=>['in',$attr_id],'attr_value'=>['in',$attr_value]])
                ->column("goods_id"); // 如果只有一个条件不再进行分组查询
        }
        return ($arr ? $arr : array_unique($arr));
    }

    /**
     * 获取地址
     * @return array
     */
    function getRegionList()
    {
        $res = S('getRegionList');
        if(!empty($res))
            return $res;
        $parent_region = Db::name('region')->field('id,name')->where(array('level'=>1))->cache(true)->select();
        $ip_location = array();
        $city_location = array();
        foreach($parent_region as $key=>$val){
            $c = Db::name('region')->field('id,name')->where(array('parent_id'=>$parent_region[$key]['id']))->order('id asc')->cache(true)->select();
            $ip_location[$parent_region[$key]['name']] = array('id'=>$parent_region[$key]['id'],'root'=>0,'djd'=>1,'c'=>$c[0]['id']);
            $city_location[$parent_region[$key]['id']] = $c;
        }
        $res = array(
            'ip_location'=>$ip_location,
            'city_location'=>$city_location
        );
        S('getRegionList',$res);
        return $res;
    }

    /**
     * 寻找Region_id的父级id
     * @param $cid
     * @return array
     */
    function getParentRegionList($cid){
        //$pids = '';
        $pids = array();
        $parent_id =  Db::name('region')->where(array('id'=>$cid))->column('parent_id');
        if($parent_id != 0){
            //$pids .= $parent_id;
            array_push($pids,$parent_id);
            $npids = $this->getParentRegionList($parent_id);
            if(!empty($npids)){
                //$pids .= ','.$npids;
                $pids = array_merge($pids,$npids);
            }

        }
        return $pids;
    }




    /**
     *网站自营,入驻商家,货到付款,仅看有货,促销商品
     * @param $sel|筛选条件
     * @param array $cat_id|分类ID
     * @return mixed
     */
    function getFilterSelected($sel ,$cat_id = array(1)){
        $where = " 1 = 1 ";
        $Goods = Db::name('goods')->where("cat_id" ,"in" ,implode(',', $cat_id));
        //查看全部
        if($sel == 'selall'){
            $where .= '';
        }
        //促销商品
        if($sel == 'prom_type'){
            $where .= ' and prom_type = 3';
        }
        //看有货
        if($sel == 'store_count'){
            $where .= ' and store_count > 0';
        }
        //看包邮
        if($sel == 'free_post'){
            $where .= ' and is_free_shipping=1';
        }
        //看全部
        if($sel == 'all'){
            $arrid = $Goods->column('goods_id');
        }else{
            $arrid = $Goods->where($where)->column('goods_id');
        }
        return $arrid;
    }

    /**
     * 是否收藏商品
     * @param type $user_id
     * @param type $goods_id
     * @return type
     */
    public function isCollectGoods($user_id, $goods_id)
    {
        $collect = Db::name('goods_collect')->where(['user_id' => $user_id, 'goods_id' => $goods_id])->find();
        return $collect ? 1 : 0;
    }


    /**
     * 获取精品商品数据
     * @return mixed
     */
    public function getRecommendGoods($p = 1)
    {
        $goods_where = array('is_recommend' => 1, 'is_on_sale' => 1);
//        $goods_where['goods_name'] = array("exp", " NOT REGEXP '华为|荣耀|小米|合约机|三星|魅族' ");//临时屏蔽,苹果APP审核过了之后注释
        $favourite_goods = Db::name('goods')
            ->field('goods_id,goods_name,shop_price,cat_id')
            ->where($goods_where)
            ->order('sort DESC')
            ->page($p, 10)
            ->cache(true, 3600)
            ->select();
        return $favourite_goods;
    }

    /**
     * 获取新品商品数据
     * @return mixed
     */
    public function getNewGoods()
    {
        $goods_where = array('is_new' => 1,  'is_on_sale' => 1);
        $orderBy = array('sort' => 'desc');
        $new_goods = Db::name('goods')
            ->field('goods_id,goods_name,shop_price')
            ->where($goods_where)
            ->order($orderBy)
            ->limit(9)
            ->select();
        return $new_goods;
    }

    /**
     * 获取热销商品数据
     * @return mixed
     */
    public function getHotGood($is_brand = 0)
    {
        $goods_where = array('is_hot' => 1,  'is_on_sale' => 1);
        if ($is_brand) {
            $goods_where['brand_id'] = ['<>', 0];
        }
        $orderBy = array('sort' => 'desc');
        $new_goods = Db::name('goods')
            ->field('goods_id,goods_name,shop_price,market_price,is_virtual')
            ->where($goods_where)
            ->order($orderBy)
            ->limit(9)
            ->select();
        return $new_goods;
    }

    /**
     * 获取首页轮播图片
     * @return mixed
     */
    public function getHomeAdv()
    {
        $start_time = strtotime(date('Y-m-d H:00:00'));
        $end_time = strtotime(date('Y-m-d H:00:00'));
        $adv = Db::name("ad")->field(array('ad_link','ad_name','ad_code'))
            ->where("pid=9 and enabled=1 and start_time< $start_time and end_time > $end_time")
            ->order("orderby desc")->cache(true,3600)
            ->limit(5)->select();
        //广告地址转换
        foreach($adv as $k=>$v){
            if(!strstr($v['ad_link'],'http')){
                $adv[$k]['ad_link'] = SITE_URL.$v['ad_link'];
            }
            $adv[$k]['ad_code'] = SITE_URL.$v['ad_code'];
        }
        return $adv;
    }

    /**
     * 获取首页轮播图片
     * @return mixed
     */
    public function getAppHomeAdv($isBanner=true)
    {
        $start_time = strtotime(date('Y-m-d H:00:00'));
        $end_time = strtotime(date('Y-m-d H:00:00'));
        if($isBanner){
            $where = array("pid"=>500);
        }else{
            $where = "pid > 500 AND pid < 520";
        }

        $adv = Db::name("ad")->field(array('ad_link','ad_name','ad_code','media_type,pid'))
            ->where(" enabled=1 and start_time< $start_time and end_time > $end_time")->where($where)
            ->order("orderby desc")//->fetchSql(true)//->cache(true,3600)
            ->limit(20)->select();

        return $adv;
    }


    /**
     * 找相似
     */
    public function getSimilar($goods_id, $p, $count)
    {
        $goods = Db::name('goods')->field('cat_id')->where('goods_id', $goods_id)->find();
        if (empty($goods)) {
            return [];
        }

        $where = ['goods_id' => ['<>', $goods_id], 'cat_id' => $goods['cat_id']];
        $goods_list = Db::name('goods')->field("goods_id,goods_name,shop_price,is_virtual")
            ->where($where)->page($p, $count)->select();

        return $goods_list;
    }



    /**
     *  获取排好序的品牌列表
     */
    function getSortBrands()
    {
        $brandList =  Db::name("brand")->select()->toArray();
        $brandIdArr =  Db::name("brand")->where("name in (select `name` from `".env('database.prefix')."brand` group by name having COUNT(id) > 1)")->column('cat_id','id');
        $goodsCategoryArr = Db::name('goods_category')->where("level = 1")->column('name','id');
        $nameList = array();
        foreach($brandList as $k => $v)
        {

            $name = getFirstCharter($v['name']) .'  --   '. $v['name']; // 前面加上拼音首字母

            if(array_key_exists($v[id],$brandIdArr) && $v['cat_id']) { // 如果有双重品牌的 则加上分类名称
                $name .= ' ( '. $goodsCategoryArr[$v['cat_id']] . ' ) ';
            }
            $nameList[] = $v['name'] = $name;
            $brandList[$k] = $v;
        }
        array_multisort($nameList,SORT_STRING,SORT_ASC,$brandList);

        return $brandList;
    }

    /**
     *  获取排好序的分类列表
     */
    function getSortCategory()
    {
        $categoryList =  Db::name("GoodsCategory")->column('id,name,parent_id,level','id');
        $nameList = array();
        foreach($categoryList as $k => $v)
        {

            //$str_pad = str_pad('',($v[level] * 5),'-',STR_PAD_LEFT);
            $name = getFirstCharter($v['name']) .' '. $v['name']; // 前面加上拼音首字母
            //$name = getFirstCharter($v['name']) .' '. $v['name'].' '.$v['level']; // 前面加上拼音首字母
            /*
            // 找他老爸
            $parent_id = $v['parent_id'];
            if($parent_id)
                $name .= '--'.$categoryList[$parent_id]['name'];
            // 找他 爷爷
            $parent_id = $categoryList[$v['parent_id']]['parent_id'];
            if($parent_id)
                $name .= '--'.$categoryList[$parent_id]['name'];
            */
            $nameList[] = $v['name'] = $name;
            $categoryList[$k] = $v;
        }
        array_multisort($nameList,SORT_STRING,SORT_ASC,$categoryList);

        return $categoryList;
    }

    /**
     * 获取类型价格
     * id==0 的情况是获取所有字段
     */
    public function getEditProductPrice($id='0'){
        $ary = [
            ['field' => 'product_no','name'=>'商品编码'],
            ['field' => 'shop_price','name'=>'零售价'],
            ['field' => 'market_price','name'=>'市场价'],
            ['field' => 'cost_price','name'=>'成本价'],
        ];
        $config = tpCache('goodsprice');
        if($config){
            foreach($config as $val){
                if(in_array($id,$val['leixing']) || $id==0){
                    //$ary[$val['field']] = $val['name'];
                    $ary[] = ['field' => $val['field'],'name'=>$val['name']];
                }
            }
        }
        $ary[] = ['field' => 'weight','name'=>'重量(KG)'];
        return $ary;
    }

    public function editgoods($params,$s_id=0){
        $goods_id = $params['goods_id']??0;
        $data = [];
        $data['sid'] = $s_id;
        if(empty($s_id) && $params['user_id']){
            $data['sid'] = $params['user_id'];
        }
        $data['leixing_id'] = $params['leixing_id'];
        $data['goods_name'] = $params['goods_name'];
        $data['goods_remark'] = $params['goods_remark'];
        $data['cat_id'] = $params['cat3']?$params['cat3']:($params['cat2']?:$params['cat1']);
        $data['cat_id_1'] = $params['cat1']?:0;
        $data['cat_id_2'] = $params['cat2']?:0;
        $data['cat_id_3'] = $params['cat3']?:0;
        $data['xgnum'] = $params['xgnum'];
        $data['qsnum'] = $params['qsnum'];
        $data['sales_sum'] = $params['sales_sum'];
        $data['original_img'] = $params['original_img'];
        $data['weight'] = intval($params['weight']);
        $data['is_free_shipping'] = $params['is_free_shipping'];
        $data['template_id'] = $params['template_id'];
        $data['store_count'] = $params['store_count'];
        $data['keywords'] = $params['keywords'];
        $data['goods_content'] = $params['goods_content'];
//        $data['goods_images'] = $params['goods_images']?implode(',',$params['goods_images']):'';
        $data['video'] = $params['video']??'';
        $data['video_duration'] = $params['video_duration']??0;
//        $data['goods_images'] = $params['goods_images']?implode(',',$params['goods_images']):'';
        $data['spec_items'] = htmlspecialchars_decode($params['specs']);
        $data['pics'] = $params['pics'];
        //多规格处理
        $ggname_arr = $params['ggname'];
        $ggname_ext_arr = $params['ggname_ext'];
        $data['ggname'] = $ggname_arr[0];
        $data['gganme_ext'] = $ggname_ext_arr[0];
        $data['on_time'] = time();
        if($s_id>0){
            $data['status'] = 0;
        }else{
            $data['status'] = $params['status']??0;
        }
        $data['reason'] = $params['reason']??'';
        if($goods_id){
            Db::name('goods')->where('goods_id',$goods_id)->update($data);
            Db::name('spec_goods_price')->where('goods_id',$goods_id)->delete();
        }else{
            $goods_id = Db::name('goods')->insertGetId($data);
        }

        $options = $params['option'];
        $pricearr = logic('GoodsLogic')->getEditProductPrice($params['leixing_id']);

        $specs = json_decode($data['spec_items'],true);

        $i = 0;
        $data_u = [];
        foreach($options as $k=>$option){
            $data_ext = [];
            $data_ext['goods_id'] = $goods_id;
            $data_ext['key'] = $k;
            $options_keys = explode(',',$k);
            $spec_name = '';

            foreach($options_keys as $k2=>$options_key){
                $spec_name .= $specs[$k2]['items'][$options_key]['title'].',';
            }
            $data_ext['key_name'] = rtrim($spec_name,',');

            foreach($pricearr as $pk=>$price_set){
                if($k==0){
                    $data_u[$price_set['field']] =  $option[$price_set['field']]??0;
                }
                $data_ext[$price_set['field']] = $option[$price_set['field']]??0;
            }
            Db::name('spec_goods_price')->insert($data_ext);
            $i++;
        }

        Db::name('goods')->where('goods_id',$goods_id)->update($data_u);

        return true;
    }
    /**
     * 获取商品信息,规格价格覆盖，其他价格覆盖等
     * @data map|order|field|
     */
    public function getListNew($data,$single=false){
        //查询条件
        $map = [];
        if(isset($data['map'])) $map = $data['map'];
        //排序
        $order = 'goods_id desc';
        if(isset($data['order'])) $order = $data['order'];

        //字段
        $field='*';
        if(isset($data['field'])) $field = $data['field'];

        //获取商品本身--默认就是第一个规格的价格
        if(isset($data['firstRow'])){
            $list = Db::name('goods')->where($map)->order($order)->field($field)->select()->toArray();
        }else{
            $list = Db::name('goods')->where($map)->order($order)->field($field)->select()->toArray();
        }
        //价格转化
        $this->getPriceNew($list,$data['user_id']??0);
        if(count($list)==1 && $single){
            return $list[0];
        }else{
            return $list;
        }
    }
    /**
     * 商品其他价格
     */
    public function getPriceNew(&$list,$user_id=0){
        //是否存在秒杀活动
        $seckill_lists = Db::name('seckill_product')
            ->where('status',1)
            ->where('stime','<=',time())
            ->where('etime','>',time())
            ->column('*','goods_id');
        foreach($list as &$val){
            if(isset($seckill_lists[$val['goods_id']])){
                $old_shop_price = $val['shop_price'];
                $seckill = $seckill_lists[$val['goods_id']];
                $price_arr = json_decode($seckill['price'],true);
                if(!empty($val['spec_goods_id'])){
                    $val['shop_price'] = $price_arr[$val['spec_goods_id']]??$val['shop_price'];
                }elseif(!empty($val['item_id'])){
                    $val['shop_price'] = $price_arr[$val['item_id']]??$val['shop_price'];
                }else{
                    $price_arr = array_values($price_arr);
                    $val['shop_price'] = $price_arr[0];
                }
                $active_youhui = bcsub($old_shop_price,$val['shop_price'],2);
                $val['is_seckill'] = 1;
                $val['active_youhui'] = $active_youhui;
                $val['store_count'] = $seckill['stock'];
                $val['etime'] = $seckill['etime'];

                $nowtime = time();
                $seckill_endtime = $seckill['etime'];
                $lefttime = $seckill_endtime - $nowtime;
                $val['hour'] = floor($lefttime / 3600);
                $val['minute'] = floor(($lefttime - $val['hour'] * 3600) / 60);
                $val['second'] = $lefttime - ($val['hour'] * 3600) - ($val['minute'] * 60);//带天数
                $val['day'] = floor($lefttime / 86400);
                $val['day_hour'] = floor(($lefttime - $val['day'] * 86400) / 3600);

            }else{
                $val['is_seckill'] = 0;
            }
        }
    }
    public function getGoodsSeckill(&$data){
        //是否存在秒杀活动
        $seckill = Db::name('seckill_product')
            ->where('status',1)
            ->where('stime','<=',time())
            ->where('etime','>',time())
            ->where('goods_id','=',$data['goods_id'])
            ->find();
        if($seckill){
            $price_arr = json_decode($seckill['price'],true);
            if(!empty($data['spec_goods_id'])){
                $data['shop_price'] = $price_arr[$data['spec_goods_id']]??$data['shop_price'];
            }elseif (!empty($data['item_id'])){
                $data['shop_price'] = $price_arr[$data['item_id']]??$data['shop_price'];
            }else{
                $price_arr = array_values($price_arr);
                $data['shop_price'] = $price_arr[0];
            }
            $data['is_seckill'] = 1;
        }else{
            $data['is_seckill'] = 0;
        }
    }
    public function getSeckillPrice($goods_id,$spec_goods_id){
        //是否存在秒杀活动
        $seckill = Db::name('seckill_product')
            ->where('status',1)
            ->where('stime','<=',time())
            ->where('etime','>',time())
            ->where('goods_id','=',$goods_id)
            ->find();
        if($seckill){
            $price_arr = json_decode($seckill['price'],true);
            $shop_price = $price_arr[$spec_goods_id]??0;
            $is_seckill = 1;
        }else{
            $shop_price = 0;
            $is_seckill = 0;
        }
        return ['status'=>1,'is_seckill'=>$is_seckill,'shop_price'=>$shop_price];
    }
}